import React from 'react'
import PropTypes from 'prop-types'
import Component, { mapStateToProps, mapDispatchToProps } from '@components/Component'
import { connect } from 'react-redux'
import { message } from 'antd'
import Approve from '@components/ApprovePre/Index'
import { requestFiles } from '@js/request'
import StepOneInput from './RequestChange/StepOneInput'
import StepOneHistory from './RequestChange/StepOneHistory'
import StepTwoInput from './RequestChange/StepTwoInput'
import StepTwoHistory from './RequestChange/StepTwoHistory'
import StepFiveInput from './RequestChange/StepFiveInput'
import StepFiveHistory from './RequestChange/StepFiveHistory'
import { awaitWrap, strToNum } from '@js/tool'

class RequestChange extends Component {
  state = {
    preKey: 'claimamend', // 表单字段前缀
    claim: { dispute_amount: 0, items: [], fee_acceptance: 0, fee_processing: 0 } // 当前请求
  }

  // 获取完整key值
  getKey (key) {
    return `${this.state.preKey}_${key}`
  }

  // 初始化当前请求
  initClaim () {
    const d = this.props.caseDetail || {}
    let claims = d.claims || []
    claims = claims.filter(li => li.status)
    const claim = claims.length ? claims[0] : { dispute_amount: 0, items: [], fee_acceptance: 0, fee_processing: 0 }
    this.setState({ claim })
  }

  // 提交前处理
  beforeSubmit (instance, data) {
    switch (instance.currentStep.step_key) {
      case 'qingqiubiangeng01':
        return this.stepOneInputBeforeSubmit(instance, data)
      case 'qingqiubiangeng02':
        return this.stepTwoInputBeforeSubmit(instance, data)
      case 'qingqiubiangeng05':
        return this.StepFiveInputBeforeSubmit(instance, data)
      default:
        return data
    }
  }

  // 第一步提交
  async stepOneInputBeforeSubmit (instance, data) {
    const hide = message.loading('文书提交中', 120)
    let fileid = ''
    const file = data.file ? data.file.fileList : []
    if (file.length) {
      const [e, d] = await awaitWrap(requestFiles(file))
      if (e) {
        return message.warning(e.message)
      }
      fileid = d.map(li => li.id).join()
    }
    hide()
    const k = this.getKey.bind(this)
    const claim = data[k('claim')]
    claim.items.forEach(li => {
      li.type = li.type[1] ? li.type[1] : li.type[0]
    })
    data.vars[k('submittalid')] = data[k('submittalid')].join()
    data.vars[k('submittal')] = data[k('submittal')].join()
    data.vars[k('create_datetime')] = Math.floor(data[k('create_datetime')] / 1000)
    data.vars[k('fileid')] = fileid
    data.vars[k('amend_type')] = data[k('amend_type')]
    data.vars[k('claim')] = JSON.stringify(claim)
    delete data.file
    delete data[k('submittalid')]
    delete data[k('submittal')]
    delete data[k('amend_type')]
    delete data[k('claim')]
    delete data[k('create_datetime')]
    return data
  }

  // 第二步提交
  stepTwoInputBeforeSubmit (instance, data) {
    const k = this.getKey.bind(this)
    const claim = data[k('claimwithfee')]
    claim.items.forEach(li => {
      li.type = li.type[1] ? li.type[1] : li.type[0]
    })
    data[k('accept_datetime')] = Math.floor(data[k('accept_datetime')] / 1000)
    data[k('log')] = claim.log
    delete claim.fee_amend
    delete claim.log
    data[k('claimwithfee')] = JSON.stringify(claim)
    const result = { remark: data.remark }
    const vars = data.vars
    delete data.vars
    delete data.remark
    result.vars = { ...vars, ...data }
    return result
  }

  // 第五步提交
  async StepFiveInputBeforeSubmit (instance, data) {
    const k = this.getKey.bind(this)
    const hide = message.loading('文件提交中', 120)
    const result = { remark: data.remark }
    let fileid = ''
    const file = data.file ? data.file.fileList : []
    if (file.length) {
      const [e, d] = await awaitWrap(requestFiles(file))
      if (e) {
        return message.warning(e.message)
      }
      fileid = d.map(li => li.id).join()
    }
    hide()
    data[k('pay_fileid')] = fileid
    data[k('pay_type')] = '线下'
    if (data[k('pay_datetime')]) {
      data[k('pay_datetime')] = Math.floor(data[k('pay_datetime')] / 1000)
    }
    if (data[k('docket_datetime')]) {
      data[k('docket_datetime')] = Math.floor(data[k('docket_datetime')] / 1000)
    }
    const vars = data.vars
    delete data.vars
    delete data.remark
    delete data.file
    result.vars = { ...vars, ...data }
    return result
  }

  // 获取第二步中的退费总额
  getPayAmountByStepTwo (list = []) {
    const { preKey } = this.state
    list = list.filter(li => li.step_key === 'qingqiubiangeng02')
    if (list.length === 0) {
      return {
        pay_amount: 0,
        fee_acceptance: 0,
        fee_processing: 0
      }
    }
    list.sort((a, b) => b.create_datetime - a.create_datetime)
    const vars = list[0].vars || []
    for (let i = 0; i < vars.length; i++) {
      const v = vars[i]
      if (v.key === `${preKey}_claimwithfee`) {
        try {
          const claim = JSON.parse(v.value)
          return {
            pay_amount: strToNum(claim.fee_acceptance_amend) + strToNum(claim.fee_processing_amend),
            fee_acceptance: strToNum(claim.fee_acceptance_amend),
            fee_processing: strToNum(claim.fee_processing_amend)
          }
        } catch (e) {
          console.warn(e)
        }
      }
    }
    return {
      pay_amount: 0,
      fee_acceptance: 0,
      fee_processing: 0
    }
  }

  // 获取表单初始化数据
  getFormInitialData (instance) {
    const { preKey } = this.state
    const o = this.getPayAmountByStepTwo(instance.history)
    switch (instance.currentStep.step_key) {
      case 'qingqiubiangeng05':
        return {
          [`${preKey}_pay_amount`]: o.pay_amount,
          [`${preKey}_fee_acceptance`]: o.fee_acceptance,
          [`${preKey}_fee_processing`]: o.fee_processing
        }
      default:
        return {}
    }
  }

  // 格式化当前步骤数据
  formatCurrentStepData (d, instance) {
    if (d.step_key === 'qingqiubiangeng01') {
      d.claim = this.props.caseDetail.claim
    } else if (d.step_key === 'qingqiubiangeng02') {
      const history = instance.history.filter(li => li.step_key === 'qingqiubiangeng01')
      history.sort((a, b) => b.complete_datetime - a.complete_datetime)
      const vars = history[0].vars
      for (let i = 0; i < vars.length; i++) {
        if (vars[i].key === this.getKey('claim')) {
          try {
            d.claim = JSON.parse(vars[i].value)
          } catch (e) {
            console.warn(e)
          }
          break
        }
      }
    }
    return d
  }

  componentDidMount () {
    this.initClaim()
  }

  // 渲染当前操作步骤线上部分
  renderCurrentStepLineTop (formRef, instance, renderFn) {
    const applicants = this.props.caseDetail.applicants.filter(li => li.status)
    switch (instance.currentStep.step_key) {
      case 'qingqiubiangeng01':
        return <StepOneInput instance={instance} userInfo={this.props.userInfo} caseDetail={this.props.caseDetail} formRef={formRef} preKey={this.state.preKey} partys={applicants} claim={this.state.claim} isChange />
      case 'qingqiubiangeng02':
        return <StepTwoInput instance={instance} userInfo={this.props.userInfo} caseDetail={this.props.caseDetail} formRef={formRef} preKey={this.state.preKey} claim={this.state.claim} />
      case 'qingqiubiangeng05':
        return <StepFiveInput instance={instance} userInfo={this.props.userInfo} caseDetail={this.props.caseDetail} formRef={formRef} preKey={this.state.preKey} partys={applicants} claim={this.state.claim} />
      default:
        return renderFn()
    }
  }

  // 渲染历史
  renderHistory (action, renderFn, instance, renderDocument) {
    const key = action.step_key
    // const isDisagree = action.opt_add === 'disagree'
    switch (key) {
      case 'qingqiubiangeng01':
        return <StepOneHistory key={action.id} userInfo={this.props.userInfo} instance={instance} action={action} renderDocument={renderDocument} preKey={this.state.preKey} />
      case 'qingqiubiangeng02':
        return <StepTwoHistory key={action.id} userInfo={this.props.userInfo} instance={instance} action={action} renderDocument={renderDocument} preKey={this.state.preKey} isRefund />
      case 'qingqiubiangeng05':
        return <StepFiveHistory key={action.id} userInfo={this.props.userInfo} instance={instance} action={action} renderDocument={renderDocument} preKey={this.state.preKey} />
    }
    return renderFn(action)
  }

  render () {
    return (
      <div>
        <Approve
          caseDetail={this.props.caseDetail}
          flowKey='qingqiubiangeng'
          // afterAction={(instance, action) => this.props.refreshCaseData()}
          renderCurrentStepLineTop={(...params) => this.renderCurrentStepLineTop(...params)}
          beforeSubmit={(...params) => this.beforeSubmit(...params)}
          renderHistory={(h, renderFn, instance, renderDocument) => this.renderHistory(h, renderFn, instance, renderDocument)}
          initialCurrentStepFormData={instance => this.getFormInitialData(instance)}
          formatCurrentStepData={(d, instance) => this.formatCurrentStepData(d, instance)}
          creatable={this.props.editable}
          afterAction={() => this.props.refreshCaseData()}
          multiply
        />
      </div>
    )
  }
}

RequestChange.propTypes = {
  caseDetail: PropTypes.object,
  // active: PropTypes.bool,
  refreshCaseData: PropTypes.func,
  editable: PropTypes.bool
  // fileList: PropTypes.array
  // getFileList: PropTypes.func
}
RequestChange.defaultProps = {
  caseDetail: {},
  active: false,
  refreshCaseData: () => {},
  editable: false,
  fileList: [],
  getFileList: () => {}
}

const mapState = mapStateToProps(function (state) {
  return {

  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {

  }
})

export default connect(mapState, mapDispatch)(RequestChange)
